package cool.taomu.toolkit.httpclient

import com.google.inject.AbstractModule
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.annotations.httpclient.HttpClient
import cool.taomu.toolkit.utils.ReflectionsScanner
import java.util.List
import java.util.Map

class ApacheHttpClientModule extends AbstractModule {

    TaomuConfigure config;

    new(TaomuConfigure configure) {
        this.config = configure
    }

    override configure() {
        this.config.binder("taomu.http.client", [
            if (it instanceof Map) {
                if ((it.get("type") as String).equalsIgnoreCase("HttpClient")) {
                    var pathList = it.get("scan")
                    if (pathList instanceof List) {
                        pathList.forEach [ path |
                            var httpInterfaces = ReflectionsScanner.scanType(HttpClient, path);
                            for (Class<?> intf : httpInterfaces) {
                                try {
                                    bind(intf as Class).toProvider(
                                        new ProxyProvider(ApacheHttpClientModule.classLoader, intf))
                                } catch (Exception e) {
                                    addError("Failed to generate implementation for %s: %s", intf.getName(),
                                        e.getMessage());
                                }
                            }
                        ]
                    }
                }
            }
        ])
    }
}
